<template>
  <div class="stock-detail">
    <TopNavBar title="股票详情" rightType="true" @rightClick="handleRightClick"  type="back" />
    <!-- 头部 -->
    <SecondContractHeader
      :coinInfo="coinInfo"
      @showSidePopup="showSidePopup"
    ></SecondContractHeader>
    <Candlestick :coinInfo="coinInfo" type="secondContract"></Candlestick>
    <!-- <div style="display: none;" class="stock-header">
      <div class="left-section">
        <div class="stock-name" @click="showStockModal = true">
          {{ stockData.symbol }}
          <van-icon name="arrow-down" class="dropdown-icon" />
        </div>
        <div class="opening-price">
          <span class="label">開盤價</span>
          <span class="value rise">{{ stockData.openingPrice }}</span>
        </div>
      </div>
      
      <div class="right-section">
        
        <div class="price-item">
          <span class="label">最高價</span>
          <span class="value rise">{{ stockData.highestPrice }}</span>
        </div>
        <div class="price-item">
          <span class="label">最低價</span>
          <span class="value fall">{{ stockData.lowestPrice }}</span>
        </div>
        <div class="price-item">
          <span class="label">最新價</span>
          <span class="value current">{{ stockData.latestPrice }}</span>
        </div>
      </div>
    </div> -->

   <div style="width: 100%;background-color: #fff;display: none;">

    <div class="chart-section">
      <!-- 时间选择器 -->
      <div class="time-intervals">
        <div 
          v-for="interval in timeIntervals" 
          :key="interval.value"
          class="interval-item"
          :class="{ active: selectedInterval === interval.value }"
          @click="selectInterval(interval.value)"
        >
          {{ interval.label }}
        </div>
        <div class="chart-settings">
          <van-icon name="setting-o" />
        </div>
      </div>
      
      <!-- 股票走势图 -->
      <div class="chart-container">
        <div ref="chartRef" class="stock-chart"></div>
        <!-- 成交量信息 -->
        <div class="volume-info">
          <span class="volume-label">VOL(5,10)</span>
          <span class="volume-value">VOL:8万↑</span>
          <span class="ma-value">MA5:8万↑</span>
        </div>
      </div>
    </div>

    <!-- 买涨买跌按钮 -->
    <div class="trading-buttons">
      <div 
        class="trade-btn buy-up"
        :class="{ active: tradeType === 'up' }"
        @click="selectTradeType('up')"
      >
        買漲
      </div>
      <div 
        class="trade-btn buy-down"
        :class="{ active: tradeType === 'down' }"
        @click="selectTradeType('down')"
      >
        買跌
      </div>
    </div>
   </div>

    <div class="trading-form">
      <!-- 选择时间 -->
      <div class="form-section">
        <div class="section-label">选择时间</div>
        <div class="time-selector" @click="showTimeModal = true">
          <span class="selected-time">{{ selectedTime }}</span>
          <van-icon name="arrow-down" class="time-dropdown" />
        </div>
      </div>

      <!-- 时间选择弹窗 -->
      <van-popup 
        v-model:show="showTimeModal" 
        position="bottom" 
        round 
        class="time-modal"
        :overlay-style="{ background: 'rgba(0, 0, 0, 0.5)' }"
      >
        <div class="modal-header">
          <div class="modal-title"> </div>
          <div class="close-btn" @click="showTimeModal = false">
            <van-icon name="cross" />
          </div>
        </div>
        <div class="time-options">
          <div 
            v-for="time in timeOptions" 
            :key="time"
            class="time-option"
            :class="{ active: selectedTime === time }"
            @click="selectTime(time)"
          >
            {{ time }}
          </div>
        </div>
      </van-popup>

      <!-- 股票选择弹窗 -->
      <van-popup 
        v-model:show="showStockModal" 
        position="bottom" 
        round 
        class="stock-modal"
        :overlay-style="{ background: 'rgba(0, 0, 0, 0.5)' }"
      >
        <div class="modal-header">
          <div class="modal-title">TSM</div>
          <div class="close-btn" @click="showStockModal = false">
            <van-icon name="cross" />
          </div>
        </div>
        <div class="stock-options">
          <div 
            v-for="stock in stockOptions" 
            :key="stock"
            class="stock-option"
            :class="{ active: stockData.symbol === stock }"
            @click="selectStock(stock)"
          >
            {{ stock }}
          </div>
        </div>
      </van-popup>

      <!-- 配资杠杆 -->
      <div class="form-section">
        <div class="section-label">配资杠杆:{{ leverageValue }}</div>
        <div class="leverage-slider">
          <div class="custom-slider" @mousedown="startDrag" @touchstart="startDrag">
            <div class="slider-track">
              <div class="slider-fill" :style="{ width: fillWidth + '%' }"></div>
            </div>
            <div 
              class="slider-thumb" 
              :style="{ left: thumbPosition + '%' }"
              @mousedown.stop="startDrag"
              @touchstart.stop="startDrag"
            >
              {{ leverageValue }}
            </div>
          </div>
        </div>
      </div>

      <!-- 购买金额 -->
      <div class="form-section">
        <div class="amount-header">
          <span class="section-label">购买金额</span>
          <span class="available-balance">可用余额:0</span>
        </div>
        <div class="amount-input">
          <van-field 
            v-model="purchaseAmount" 
            placeholder=">=1000" 
            type="number"
            class="amount-field"
          />
        </div>
      </div>

      <!-- 预估收益 -->
      <div class="estimated-earnings">
        预估收益:0
      </div>
    </div>

    <div class="confirm-section">
      <van-button type="primary" block class="confirm-btn">确认</van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Icon as VanIcon, Button as VanButton, Field as VanField, Popup as VanPopup } from 'vant'
import * as echarts from 'echarts'
import TopNavBar from '@/components/common/TopNavBar.vue'
import Candlestick from '../trade/components/common/candlestick.vue'
import SecondContractHeader from '../trade/components/secondContract/header/index.vue' // 秒合约header部分
import { useTradeStore } from '@/store/trade'

const route = useRoute()
const router = useRouter()
const stockSymbol = route.params.symbol || 'TSM'
const tradeStore = useTradeStore()

/**
 * 侧边栏
 */
const sidePopup = ref(false)
const showSidePopup = () => {
  sidePopup.value = true
}

// 图表相关
const chartRef = ref(null)
let chartInstance = null
const selectedInterval = ref('1m')

// 时间间隔选项
const timeIntervals = [
  { label: '1m', value: '1m' },
  { label: '15m', value: '15m' },
  { label: '30m', value: '30m' },
  { label: '1D', value: '1D' },
  { label: '1W', value: '1W' },
  { label: '1M', value: '1M' }
]

// 模拟K线数据
const generateKLineData = () => {
  const data = []
  const basePrice = 237.5
  const baseTime = new Date('2025-07-17 03:30:00').getTime()
  
  // 生成一个更真实的股票走势
  let currentPrice = basePrice
  let trend = 0 // 趋势：-1下降，0震荡，1上升
  
  for (let i = 0; i < 30; i++) {
    const time = baseTime + i * 60000 // 每分钟一个数据点
    
    // 随机改变趋势
    if (Math.random() < 0.3) {
      trend = Math.floor(Math.random() * 3) - 1
    }
    
    // 根据趋势调整价格
    let priceChange = 0
    if (trend === 1) {
      priceChange = (Math.random() * 0.8 + 0.2) * (Math.random() < 0.7 ? 1 : -1)
    } else if (trend === -1) {
      priceChange = (Math.random() * 0.8 + 0.2) * (Math.random() < 0.7 ? -1 : 1)
    } else {
      priceChange = (Math.random() - 0.5) * 0.6
    }
    
    const open = currentPrice
    const close = currentPrice + priceChange
    const high = Math.max(open, close) + Math.random() * 0.3
    const low = Math.min(open, close) - Math.random() * 0.3
    const volume = Math.floor(Math.random() * 40000) + 40000
    
    data.push([
      time,
      open.toFixed(4),
      close.toFixed(4),
      high.toFixed(4),
      low.toFixed(4),
      volume
    ])
    
    currentPrice = close
  }
  
  return data
}

const stockData = ref({
  symbol: stockSymbol,
  openingPrice: '234.6',
  highestPrice: '240.5',
  lowestPrice: '236.38',
  latestPrice: '240.33'
})

// console.log(stockSymbol);
const coinInfo = computed(() =>
  tradeStore.secondContractCoinList.find((it) => it.coinUpperCase === stockSymbol)
)
// console.log(coinInfo)

const leverageValue = ref(1)
const purchaseAmount = ref('')
const isDragging = ref(false)
const showTimeModal = ref(false)
const showStockModal = ref(false)
const selectedTime = ref('3小时')
const tradeType = ref('up') // 交易类型：'up' 买涨, 'down' 买跌，默认选中买涨

const timeOptions = [
  '1小时',
  '2小时', 
  '3小时',
  '4小时',
  '6小时',
  '8小时',
  '12小时',
  '24小时'
]

const stockOptions = [
  'TSM',
  'NVIDIA',
  'Apple Inc',
  'HMC',
  'TSLA',
  'RACE',
  'ETR',
  'CMI',
  'VLO',
  'SHEL',
  'CLMT',
  'NI',
  'ALB',
  'ENPH',
  'NEE',
  'WOLF',
  'STEM',
  'AMRC'
]

// 选择时间间隔
const selectInterval = (interval) => {
  selectedInterval.value = interval
  updateChart()
}

// 选择时间方法
const selectTime = (time) => {
  selectedTime.value = time
  showTimeModal.value = false
}

// 选择股票方法
const selectStock = (stock) => {
  stockData.value.symbol = stock
  showStockModal.value = false
}

// 选择交易类型方法
const selectTradeType = (type) => {
  tradeType.value = type
}

// 处理右侧按钮点击
const handleRightClick = () => {
  router.push('/order-list')
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
  updateChart()
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    chartInstance && chartInstance.resize()
  })
}

// 更新图表数据
const updateChart = () => {
  if (!chartInstance) return
  
  const klineData = generateKLineData()
  const volumeData = klineData.map(item => [item[0], item[5]])
  
  const option = {
    backgroundColor: '#ffffff',
    animation: false,
    legend: {
      show: false
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: 'transparent',
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      formatter: function(params) {
        const klineData = params[0].data
        const volumeData = params[1] ? params[1].data : 0
        const time = params[0].axisValue
        
        return `
          <div style="padding: 8px;">
            <div style="margin-bottom: 4px;">时间: ${time}</div>
            <div style="margin-bottom: 4px;">开盘: ${klineData[0]}</div>
            <div style="margin-bottom: 4px;">收盘: ${klineData[1]}</div>
            <div style="margin-bottom: 4px;">最高: ${klineData[2]}</div>
            <div style="margin-bottom: 4px;">最低: ${klineData[3]}</div>
            <div>成交量: ${(volumeData / 10000).toFixed(1)}万</div>
          </div>
        `
      }
    },
    grid: [
      {
        left: '10%',
        right: '10%',
        top: '15%',
        height: '60%'
      },
      {
        left: '10%',
        right: '10%',
        top: '80%',
        height: '15%'
      }
    ],
    xAxis: [
      {
        type: 'category',
        data: klineData.map(item => {
          const date = new Date(item[0])
          return date.toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
          })
        }),
        scale: true,
        boundaryGap: false,
        axisLine: { onZero: false },
        splitLine: { show: false },
        splitNumber: 20,
        min: 'dataMin',
        max: 'dataMax',
        axisLabel: {
          color: '#666',
          fontSize: 10
        }
      },
      {
        type: 'category',
        gridIndex: 1,
        data: klineData.map(item => {
          const date = new Date(item[0])
          return date.toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
          })
        }),
        scale: true,
        boundaryGap: false,
        axisLine: { onZero: false },
        splitLine: { show: false },
        splitNumber: 20,
        min: 'dataMin',
        max: 'dataMax',
        axisLabel: { show: false }
      }
    ],
    yAxis: [
      {
        scale: true,
        position: 'right',
        splitArea: {
          show: true
        },
        axisLabel: {
          color: '#666',
          fontSize: 10,
          formatter: function(value) {
            return value.toFixed(4)
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: '#f0f0f0',
            type: 'dashed'
          }
        }
      },
      {
        scale: true,
        gridIndex: 1,
        splitNumber: 2,
        axisLabel: { show: false },
        axisLine: { show: false },
        axisTick: { show: false },
        splitLine: { show: false }
      }
    ],
    dataZoom: [
      {
        type: 'inside',
        xAxisIndex: [0, 1],
        start: 0,
        end: 100
      }
    ],
    series: [
      {
        name: 'K线',
        type: 'candlestick',
        data: klineData.map(item => item.slice(1, 5)),
        itemStyle: {
          color: '#e14c4c',
          color0: '#0bb07b',
          borderColor: '#e14c4c',
          borderColor0: '#0bb07b'
        }
      },
      {
        name: '成交量',
        type: 'bar',
        xAxisIndex: 1,
        yAxisIndex: 1,
        data: volumeData.map(item => item[1]),
        itemStyle: {
          color: function(params) {
            const klineItem = klineData[params.dataIndex]
            return klineItem[2] >= klineItem[1] ? '#0bb07b' : '#e14c4c'
          }
        }
      }
    ]
  }
  
  chartInstance.setOption(option)
}

// 计算属性
const fillWidth = computed(() => {
  return ((leverageValue.value - 1) / 9) * 100
})

const thumbPosition = computed(() => {
  return ((leverageValue.value - 1) / 9) * 100
})

// 滑块拖拽逻辑
const startDrag = (event) => {
  event.preventDefault()
  event.stopPropagation()
  isDragging.value = true
  document.addEventListener('mousemove', handleDrag)
  document.addEventListener('mouseup', stopDrag)
  document.addEventListener('touchmove', handleDrag, { passive: false })
  document.addEventListener('touchend', stopDrag)
  handleDrag(event)
}

const handleDrag = (event) => {
  if (!isDragging.value) return
  
  event.preventDefault()
  event.stopPropagation()
  
  const slider = event.target.closest('.custom-slider')
  if (!slider) return
  
  const rect = slider.getBoundingClientRect()
  const clientX = event.clientX || (event.touches && event.touches[0].clientX)
  const offsetX = clientX - rect.left
  const percentage = Math.max(0, Math.min(100, (offsetX / rect.width) * 100))
  
  // 将百分比转换为1-10的值
  const value = Math.round((percentage / 100) * 9) + 1
  leverageValue.value = Math.max(1, Math.min(10, value))
}

const stopDrag = (event) => {
  if (event) {
    event.preventDefault()
    event.stopPropagation()
  }
  isDragging.value = false
  document.removeEventListener('mousemove', handleDrag)
  document.removeEventListener('mouseup', stopDrag)
  document.removeEventListener('touchmove', handleDrag)
  document.removeEventListener('touchend', stopDrag)
}

onMounted(async () => {
  await nextTick()
  initChart()
  console.log('Stock symbol:', stockSymbol)
})

onUnmounted(() => {
  stopDrag()
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped>
.stock-detail {
  background: #f6f8fa;
  min-height: 100vh;
}

.stock-header {
  background: #fff;
  padding: 20px 16px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.left-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stock-name {
  font-size: 20px;
  font-weight: 700;
  color: #222;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: color 0.2s ease;
}

.stock-name:hover {
  color: #0bb07b;
}

.dropdown-icon {
  color: #666;
  font-size: 14px;
}

.opening-price {
  display: flex;
  align-items: center;
  gap: 4px;
}

.opening-price .label {
  font-size: 12px;
  color: #666;
  margin-right: 10px;
}

.opening-price .value {
  font-size: 16px;
  font-weight: 600;
}

.right-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.price-item {
  display: flex;
  align-items: center;
  align-items: flex-end;
  gap: 4px;
}

.price-item .label {
  font-size: 11px;
  color: #666;
  margin-right: 70px;
}

.price-item .value {
  font-size: 14px;
  font-weight: 600;
}

.value.rise {
  color: #0bb07b;
}

.value.fall {
  color: #e14c4c;
}

.value.current {
  color: #222;
}

.chart-section {
  background: #fff;
  border-radius: 12px;
}

/* 时间选择器样式 */
.time-intervals {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 0 8px;
}

.interval-item {
  padding: 6px 12px;
  font-size: 12px;
  color: #666;
  background: transparent;
  border-radius: 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  user-select: none;
}

.interval-item:hover {
  background: #f5f5f5;
}

.interval-item.active {
  background: #222;
  color: #fff;
  font-weight: 600;
}

.chart-settings {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #222;
  border-radius: 4px;
  cursor: pointer;
}

.chart-settings .van-icon {
  color: #fff;
  font-size: 14px;
}

/* 图表容器样式 */
.chart-container {
  width: 100%;
  height: 280px;
  position: relative;
}

.stock-chart {
  width: 100%;
  height: 100%;
}

.volume-info {
  position: absolute;
  top: 10px;
  left: 10px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  padding: 4px 8px;
  border-radius: 8px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  z-index: 10;
}

.volume-label {
  font-weight: 600;
}

.volume-value {
  font-weight: 600;
  color: #ffeb3b; /* 成交量使用黄色 */
}

.ma-value {
  font-weight: 600;
  color: #2196f3; /* MA值使用蓝色 */
}

.trading-buttons {
  display: flex;
  justify-content: space-between;
  margin: 0 16px 12px 16px;
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  gap: 12px;
}

.trade-btn {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #fff;
  background-color: #979797;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  user-select: none;
}

.trade-btn.active {
  color: #fff;
}

.trade-btn.buy-up.active {
  background-color: #00D77C;
}

.trade-btn.buy-down.active {
  background-color: #FF4834;
}

.trade-btn:hover:not(.active) {
  background-color: #b0b0b0;
}

.trading-form {
  background: #fff;
  padding: 20px 16px;
}

.form-section {
  margin-bottom: 20px;
}

.section-label {
  font-size: 14px;
  color: #222;
  margin-bottom: 8px;
  font-weight: 500;
}

.time-selector {
  background: #f5f5f5;
  border-radius: 8px;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-time {
  font-size: 14px;
  color: #222;
}

.time-dropdown {
  color: #666;
  font-size: 12px;
}

/* 时间选择弹窗样式 */
.time-modal {
  border-radius: 16px 16px 0 0;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 16px 16px 16px;
  border-bottom: 1px solid #f0f0f0;
  background: #f8f8f8;
  border-radius: 16px 16px 0 0;
}

.modal-title {
  font-size: 16px;
  font-weight: 600;
  color: #222;
  flex: 1;
  text-align: center;
}

.close-btn {
  width: 32px;
  height: 32px;
  background: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.close-btn .van-icon {
  color: #666;
  font-size: 16px;
}

.time-options {
  padding: 16px;
  max-height: 300px;
  overflow-y: auto;
}

.time-option {
  padding: 16px 0;
  text-align: center;
  font-size: 16px;
  color: #222;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.time-option:last-child {
  border-bottom: none;
}

.time-option:hover {
  background: #f5f5f5;
}

.time-option.active {
  color: #0bb07b;
  font-weight: 600;
}

/* 股票选择弹窗样式 */
.stock-modal {
  border-radius: 16px 16px 0 0;
}

.stock-options {
  padding: 16px;
  max-height: 400px;
  overflow-y: auto;
  padding-top: 0;
}

.stock-option {
  padding: 16px 0;
  text-align: center;
  font-size: 16px;
  color: #222;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.stock-option:last-child {
  border-bottom: none;
}

.stock-option:hover {
  background: #f5f5f5;
}

.stock-option.active {
  color: #0bb07b;
  font-weight: 600;
}

.leverage-slider {
  position: relative;
  padding: 20px 0 8px 0;
}

.custom-slider {
  position: relative;
  width: 100%;
  height: 40px;
  cursor: pointer;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.slider-track {
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 4px;
  background: #e0e0e0;
  border-radius: 2px;
  transform: translateY(-50%);
  pointer-events: none;
}

.slider-fill {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background: #222;
  border-radius: 2px;
  transition: width 0.1s ease;
  pointer-events: none;
}

.slider-thumb {
  position: absolute;
  top: 50%;
  width: 24px;
  height: 24px;
  background: #222;
  border-radius: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  transition: left 0.1s ease;
  z-index: 10;
  touch-action: none;
}

.slider-thumb:hover {
  transform: translate(-50%, -50%) scale(1.1);
}

.slider-thumb:active {
  transform: translate(-50%, -50%) scale(1.05);
}

.amount-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.available-balance {
  font-size: 12px;
  color: #666;
}

.amount-input {
  background: #f5f5f5;
  border-radius: 8px;
  overflow: hidden;
}

.amount-field {
  background: transparent;
  border: none;
  padding: 12px 16px;
}

.amount-field :deep(.van-field__control) {
  background: transparent;
  border: none;
  font-size: 14px;
  color: #222;
}

.amount-field :deep(.van-field__control::placeholder) {
  color: #999;
}

.estimated-earnings {
  text-align: right;
  font-size: 14px;
  color: #666;
  margin-top: 16px;
}

.confirm-section {
  padding: 0 16px 20px 16px;
}

.confirm-btn {
  background: #222;
  border: none;
  border-radius: 8px;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  color: #fff;
}
</style> 